#include "rclcpp/rclcpp.hpp"
#include "base_interfaces_demo/srv/add_ints.hpp"

using base_interfaces_demo::srv::AddInts;
using namespace std::chrono_literals;

class MyClient:public rclcpp::Node{
    public:
    MyClient():Node("myclient"){
        
        client = this->create_client<AddInts>("Add");
        RCLCPP_INFO(this->get_logger(),"client ok");


    }

    bool connect_server(){
        while (!client->wait_for_service(1s))
        {
            if(!rclcpp::ok())
            {
                RCLCPP_INFO(this->get_logger(),"exit");
                return false;
            }

            RCLCPP_INFO(this->get_logger(),"wait...");
        }
        return true;
    }


    rclcpp::Client<AddInts>::FutureAndRequestId send_request(int32_t num1,int32_t num2){
        auto request = std::make_shared<AddInts::Request>();
        request->num1 = num1;
        request->num2 = num2;
        return client->async_send_request(request);
    }
    private:
    rclcpp::Client<AddInts>::SharedPtr client;
};


int main(int argc,char** argv)
{
    if(argc != 3){
        RCLCPP_INFO(rclcpp::get_logger("rclcpp"),"input 3 int");
        return 1;
    }

    rclcpp::init(argc,argv);

    auto client = std::make_shared<MyClient>();
    bool flag = client->connect_server();

    if(!flag)
    {
        RCLCPP_INFO(rclcpp::get_logger("rclcpp"),"false");
        return 0;
    }


    auto response = client->send_request(atoi(argv[1]),atoi(argv[2]));

    if(rclcpp::spin_until_future_complete(client,response) == rclcpp::FutureReturnCode::SUCCESS)
    {
        RCLCPP_INFO(client->get_logger(),"请求正常处理");
        RCLCPP_INFO(client->get_logger(),"响应结果:%d!", response.get()->sum);
    }else {
        RCLCPP_INFO(client->get_logger(),"请求异常");
    }

    rclcpp::shutdown();
    return 0;
}